package wf.source.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置类里声明了交换机
 Bean的名称和交换机对应 或队列对应
 把队列绑定到交换机
 一个交换机 里面绑定了2个队列 #表示一个或多个
 */
@Configuration
public class RabbitmqConfig {
    public static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    public static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    public static final String EXCHANGE_FANOUT_INFORM = "exchange_fanout_inform";

    /**
     * 交换机配置
     * ExchangeBuilder提供了fanout、direct、fanout、header交换机类型的配置
     *
     * @return the exchange
     */
    @Bean(EXCHANGE_FANOUT_INFORM)
    public Exchange EXCHANGE_FANOUT_INFORM() {
        //durable(true)持久化，消息队列重启后交换机仍然存在
        return ExchangeBuilder.fanoutExchange(EXCHANGE_FANOUT_INFORM).durable(true).build();
    }

    //声明队列
    @Bean(QUEUE_INFORM_SMS)
    public Queue QUEUE_INFORM_SMS() {
        Queue queue = new Queue(QUEUE_INFORM_SMS);
        return queue;
    }

    //声明队列
    @Bean(QUEUE_INFORM_EMAIL)
    public Queue QUEUE_INFORM_EMAIL() {
        Queue queue = new Queue(QUEUE_INFORM_EMAIL);
        return queue;
    }

    /**
     * channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
     * 绑定队列到交换机 .
     *
     * @param queue    the queue
     * @param exchange the exchange
     * @return the binding
     * @Autowired(QUEUE_INFORM_SMS) 正常来说使用Autowired来注入，但是现在Queue有两个，
     * 用它就会报错，要用@Qualifier(QUEUE_INFORM_SMS)
     */
    @Bean
    public Binding BINDING_QUEUE_INFORM_SMS(@Qualifier(QUEUE_INFORM_SMS) Queue queue,
                                            @Qualifier(EXCHANGE_FANOUT_INFORM) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("hrm.send.phone.message").noargs();
    }

    @Bean
    public Binding BINDING_QUEUE_INFORM_EMAIL(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue,
                                              @Qualifier(EXCHANGE_FANOUT_INFORM) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("hrm.send.email.message").noargs();
    }

}
